package cn.akwangl.spring.dependency.inject;

import cn.akwangl.spring.dependency.inject.model.UserHolder;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;

/**
 * 通过 Java API 构造器注入示例
 *
 * @author youyongkun
 * @date 2021/7/18 9:53 上午
 */
public class ApiDependencyConstructorInjectDemo {

    public static void main(String[] args) {
        DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();

        // API 注册BeanDefinition
        BeanDefinition userHolderBeanDefinition = createUserHolderBeanDefinition();
        beanFactory.registerBeanDefinition("userHolder", userHolderBeanDefinition);

        XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(beanFactory);
        String location = "classpath:/META-INF/dependency-lookup-context.xml";
        xmlReader.loadBeanDefinitions(location);

        UserHolder userHolder = beanFactory.getBean(UserHolder.class);
        System.out.println(userHolder);
    }

    public static BeanDefinition createUserHolderBeanDefinition() {
        BeanDefinitionBuilder genericBeanDefinition = BeanDefinitionBuilder.genericBeanDefinition(UserHolder.class);
        // 构造器参数绑定
        genericBeanDefinition.addConstructorArgReference("superUser");
        return genericBeanDefinition.getBeanDefinition();
    }
}
